import { defineStore } from "pinia";
import { SeniorFileItem } from "@/entity/SeniorFileItem";
import {
  UseSeniorFileItemContent,
  useSeniorFileItemContent
} from "@/hooks/query/SeniorFileItemContent";

interface TabOption {
  label: string;
  value: string;
}

export const useSeniorSearchStore = defineStore("useSeniorSearchStore", () => {
  // 所在目录
  const parentId = ref("0");
  const activeIds = ref(new Array<TabOption>());
  const activeId = ref("");
  const contentMap = new Map<string, UseSeniorFileItemContent>();

  const contents = computed<Array<UseSeniorFileItemContent>>(() =>
    activeIds.value.map((e) => {
      const source = contentMap.get(e.value);
      if (source) return source;
      else {
        const target = useSeniorFileItemContent(e.value);
        contentMap.set(e.value, target);
        return target;
      }
    })
  );

  const onFileItemClick = (item: SeniorFileItem) => {
    if (item.folder) {
      parentId.value = item.id;
    } else {
      // 文件点击，打开
      if (!activeIds.value.find((e) => e.value === item.id)) {
        activeIds.value.push({
          label: item.name,
          value: item.id
        });
      }
      activeId.value = item.id;
    }
  };
  const onFileItemClose = (id: string) => {
    activeIds.value = activeIds.value.filter((i) => i.value !== id);
    contentMap.delete(id);
    if (activeId.value === id)
      activeId.value = activeIds.value[activeIds.value.length - 1]?.value || "";
  };

  const getFileContent = (id: string): UseSeniorFileItemContent => {
    const source = contentMap.get(id);
    if (source) return source;
    const target = useSeniorFileItemContent(id);
    contentMap.set(id, target);
    return target;
  };

  // TODO: 需要允许临时文件的存在，并且第一个也是临时文件
  const loadEvent = (props: { link: string; method: string; body: string }) => {};

  return {
    parentId,
    activeId,
    activeIds,
    contents,
    onFileItemClick,
    onFileItemClose,
    getFileContent,
    loadEvent
  };
});
